/*
 * Copyright (c) 2007-2020 西安交通信息投资营运有限公司 版权所有
 * 作者:马星俊
 */

import React, {FC, SetStateAction, useCallback, useEffect, useState} from "react";
import {Button, Form, message, Modal, Radio, Skeleton, Spin, Steps} from "antd";
import styles from "./Authorize.less";
import {DialogOperate} from "@/global";
import {PermissionModel} from "@/pages/sys/role/data";
import permissionService from "@/pages/sys/permission/service";
import {getCurrentUserId, newDelay} from "@/utils/utils";
import deptService from "@/pages/sys/dept/service";
import {MessageType} from "antd/lib/message";
import DeptTree from "@/pages/sys/role/components/DeptTree";
import FunctionTree from "@/pages/sys/role/components/FunctionTree";


/** 系统角色授权表单组件 */
const Authorize: FC<DialogOperate> = (props) => {
  const {params: {ids, data, onSubmitSucess}, visible, hide} = props;
  const [loading, setLoading] = useState<boolean>(false);
  const [currentStep, setCurrentStep] = useState<number>(0);
  const [formProps, setFormProps] = useState<Partial<PermissionModel>>({
    deptScope: ids.length == 1 ? data[0].deptScope : 5,
    roleIds: ids.join()
  })
  /** 功能权限树属性 */
  const [functionTree, setFunctionTree] = useState<SetStateAction<any>>({tree: [], checks: []});
  const [deptTree, setDeptTree] = useState<SetStateAction<any>>({tree: [], checks: []});

  useEffect(() => {
    let hideMessage: MessageType;
    const delay = newDelay();
    delay.run(() => hideMessage = message.loading('正在加载...'));

    fetchData().then(() => {
      setLoading(false);
      delay.finish(() => hideMessage && hideMessage());
    }).catch(() => delay.finish(() => hideMessage && hideMessage()));
  }, [ids])
  const [form] = Form.useForm();
  const FormItem = Form.Item;

  /** 获取组件初始化数据*/
  const fetchData = async () => {
    const userPer = await permissionService.selectUserPermissionModules(getCurrentUserId());
    const deptList = await deptService.selectTreeList({});
    const funChecks: string[] = [];
    const deptChecks: string[] = [];
    const defaultFunChecks: string[] = [];
    let rolePer;
    if (formProps.roleIds) {
      let ids = formProps.roleIds.split(",")
      if (ids.length == 1) {
        rolePer = await permissionService.selectRolePermission(formProps.roleIds)
        clear(userPer.data)
        if (rolePer.data.deptScopePermission.customs) {
          for (let i = 0; i < rolePer.data.deptScopePermission.customs.length; i++) {
            const id: string = rolePer.data.deptScopePermission.customs[i].id;
            if (!map[id]) {
              deptChecks.push(id);
            }
          }
        }
        if (rolePer.data.modules) {
          for (let i = 0; i < rolePer.data.modules.length; i++) {
            const id: string = rolePer.data.modules[i].id;
            defaultFunChecks.push(id);
            if (!map[id]) {
              funChecks.push(id);
            }
          }
        }
        ;
      }
    }
    const funData = {tree: userPer.data, checks: funChecks};
    setFunctionTree(funData);
    const deptData = {tree: deptList.data, checks: deptChecks};
    setDeptTree(deptData);
    setFormProps({...formProps, moduleIds: defaultFunChecks.join(), customDeptIds: deptData.checks.join()})
  }

  const map = {};

  /** 查询list中的所有父节点*/
  function clear(list: any[]) {
    for (let i = 0; i < list.length; i++) {
      const item: any = list[i];
      if (item.children) {
        map[item.key] = item;
        clear(item.children);
      }
    }
  }

  /** 授权操作组件 */
  const useSave = function authorize() {
    const submitSuccessMessage = '授权成功';

    const [submitLoading, setSubmitLoading] = useState(false);

    /** 提交函数  */
    const setSubmit = useCallback((PermissionModel: PermissionModel) => {
      setSubmitLoading(true);
      permissionService.saveRolePermission(PermissionModel).then(r => {
        setSubmitLoading(false)
        if (r.success) {
          submitSuccessMessage && message.success({content: submitSuccessMessage, duration: 1});
        }
      }).catch(() => setSubmitLoading(false));
    }, [submitSuccessMessage]);


    return {
      submitLoading,
      setSubmit,
    };
  }
  const {submitLoading, setSubmit} = useSave();

  const {Step} = Steps;
  const next = () => setCurrentStep(currentStep + 1);
  const back = () => {
    setCurrentStep(currentStep - 1);
    form.setFieldsValue({...form.getFieldsValue(), ...formProps});
  };
  const handleNext = async () => {
    if (currentStep < 1) {
      next();
    } else {
      setSubmit(formProps as PermissionModel);
      hide();
      onSubmitSucess && onSubmitSucess();
    }
  };

  const onChange = (e: any) => {
    setFormProps({...formProps, deptScope: e.target.value});
  };

  const handFuncTree = (keys: any, info: any) => {
    setFormProps({...formProps, moduleIds: [...keys, ...info].join()});
    setFunctionTree({...functionTree, checks: [...keys]})
    form.setFieldsValue({...form.getFieldsValue(), "moduleIds": [...keys, ...info].join()});
  }
  const handDeptTree = (keys: any) => {
    setFormProps({...formProps, customDeptIds: keys.join()});
    setDeptTree({...deptTree, checks: [...keys]})
    form.setFieldsValue({...form.getFieldsValue(), "customDeptIds": keys.join()});
  }

  const renderContent = () => {
    if (currentStep === 1) {
      return (
        <>
          <FormItem name="deptScope">
            <Radio.Group onChange={onChange}>
              <Radio value={1}>全部</Radio>
              <Radio value={2}>自定义</Radio>
              <Radio value={3}>所在机构及所有下级</Radio>
              <Radio value={4}>所在机构</Radio>
              <Radio value={5}>仅本人</Radio>
            </Radio.Group>
          </FormItem>
          <div style={{position: 'relative'}}>
            <div style={{overflow: 'auto'}}>
              <FormItem name="customDeptIds">
                <Skeleton loading={loading} active paragraph={{rows: 7, width: [200, 300, 200, 300, 200, 300]}}>
                  <DeptTree treeData={deptTree} onChange={handDeptTree}/>
                </Skeleton>
              </FormItem>
            </div>
            <div id="dept-tree-background" className={formProps?.deptScope === 2 ? '' : styles.treeBackground}/>
          </div>
        </>
      );
    }
    return (
      <>
        <FormItem name="moduleIds">
          <Skeleton loading={loading} active paragraph={{rows: 7, width: [200, 300, 200, 300, 200, 300]}}>
            <FunctionTree tree={functionTree.tree} value={functionTree.checks} onChange={handFuncTree}/>
          </Skeleton>
        </FormItem>
      </>
    );
  };
  const renderFooter = () => {
    if (currentStep === 1) {
      return (
        <>
          <Button style={{float: 'left'}} onClick={back}>
            上一步
          </Button>
          <Button onClick={hide}>取消</Button>
          <Button type="primary" onClick={() => handleNext()}>
            完成
          </Button>
        </>
      );
    }

    return (
      <>
        <Button onClick={hide}>取消</Button>
        <Button type="primary" onClick={() => handleNext()}>
          下一步
        </Button>
      </>
    );
  };

  return (
    <Modal
      title="角色授权"
      visible={visible}
      width={640}
      destroyOnClose
      maskClosable={false}
      onCancel={hide}
      footer={renderFooter()}
    >
      <Spin
        spinning={loading || submitLoading} wrapperClassName={styles.h100p}
      >
        {formProps && (<Form
          form={form}
          initialValues={formProps}
        >
          <Steps type="navigation" style={{marginBottom: 28}} size="small" current={currentStep}>
            <Step title="功能权限"/>
            <Step title="机构权限"/>
          </Steps>
          {renderContent()}
        </Form>)}
      </Spin>
    </Modal>
  );


}
export default Authorize;
